package com.xz.web.controller.message;

import com.alibaba.fastjson.JSONObject;
import com.xz.common.annotation.Log;
import com.xz.common.core.controller.BaseController;
import com.xz.common.core.domain.AjaxResult;
import com.xz.common.enums.BusinessType;
import com.xz.common.utils.Constant;
import com.xz.common.utils.SecurityUtils;
import com.xz.message.domain.SysTenantNotifyConfig;
import com.xz.message.service.ISysTenantNotifyConfigService;
import com.xz.message.utils.DdapiUtil;
import com.xz.message.utils.QyapiUtil;
import com.xz.message.vo.DeptUser;
import com.xz.message.vo.MessageBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 租户消息通知配置Controller
 *
 * @author xz
 * @date 2023-08-04
 */
@RestController
@RequestMapping("/notify")
public class MessageTestController extends BaseController {
    @Autowired
    private ISysTenantNotifyConfigService sysTenantNotifyConfigService;
    @Autowired
    private QyapiUtil qyapiUtil;
    @Autowired
    private DdapiUtil ddapiUtil;

    private static final Logger log = LoggerFactory.getLogger(MessageTestController.class);

    /**
     * 获取部门成员
     * type 1企业微信 2钉钉
     */
    @GetMapping("/getbymobile")
    public AjaxResult getbymobile(String mobile,Integer type)
    {
        SysTenantNotifyConfig tenantConfig = sysTenantNotifyConfigService.selectNotifyConfigByTenantId(SecurityUtils.getLoginUser().getTenantId());
        try {
            if(type == 1){
                //从2022年8月15日10点开始，“企业管理后台 - 管理工具 - 通讯录同步”的新增IP将不能再调用此接口
//                return AjaxResult.success(qyapiUtil.getbymobile(tenantConfig,mobile));
                String userId = qyapiUtil.getUserIdbymobile(tenantConfig, mobile);
                List<DeptUser> list = qyapiUtil.getDepartmentMembers(tenantConfig);
                DeptUser deptUser = list.stream().filter(i -> i.getUserid().equals(userId)).findFirst().orElse(new DeptUser());
                return AjaxResult.success(deptUser);
            }else if(type == 2){
                return AjaxResult.success(ddapiUtil.getbymobile(tenantConfig,mobile));
            }else{
                return AjaxResult.success();
            }
        }catch (Exception e){
            log.error("根据手机号获取成员企微或钉钉信息异常,mobile="+mobile+",type="+type+",tenantId="+tenantConfig.getTenantId());
            log.error("根据手机号获取成员企微或钉钉信息异常,err="+e);
            return AjaxResult.error("查询失败,请联系管理员");
        }
    }

    /**
     * 获取部门成员
     */
    @GetMapping("/getDepartmentMembers")
    public AjaxResult getDepartmentMembers()
    {
        SysTenantNotifyConfig tenantConfig = sysTenantNotifyConfigService.selectNotifyConfigByTenantId(SecurityUtils.getLoginUser().getTenantId());
        HashMap<Object, Object> map = new HashMap<>();
       if(Constant.ENABLED==tenantConfig.getQyEnable()){
           List<DeptUser> list = qyapiUtil.getDepartmentMembers(tenantConfig);
           map.put("qyEnable",true);
           map.put("qwUserOptions",list);
       }else{
           map.put("qyEnable",false);
           map.put("qwUserOptions",new ArrayList<>());
       }
        return AjaxResult.success(map);
    }

    /**
     * 发送应用消息
     */
    @Log(title = "发送应用消息", businessType = BusinessType.INSERT)
    @PostMapping("/sendMsg")
    public AjaxResult sendMsg(String touser,  String content)
    {
        SysTenantNotifyConfig tenantConfig = sysTenantNotifyConfigService.selectNotifyConfigByTenantId(SecurityUtils.getLoginUser().getTenantId());
        MessageBody messageBody = new MessageBody(touser,tenantConfig.getQyAgentId(),content);
        return AjaxResult.success(qyapiUtil.sendMsg(tenantConfig,messageBody));
    }


    /**
     * 发送机器人消息
     */
    @Log(title = "发送机器人消息", businessType = BusinessType.INSERT)
    @PostMapping("/sendWebhook")
    public AjaxResult sendWebhook(String webhook,  String content)
    {
        MessageBody messageBody = new MessageBody(content);
        qyapiUtil.sendWebhook(webhook,messageBody);
        return AjaxResult.success();
    }
    /**
     * 企业微信回调
     * 3.1 支持Http Get请求验证URL有效性
     * 3.2 支持Http Post请求接收业务数据
     *
     * @return
     */
    @RequestMapping(value = "/getCallBack", method = {RequestMethod.GET, RequestMethod.POST})
    public Object CompanyWeChatChangeNotice(HttpServletRequest request, @RequestBody(required = false) String body) {
        Map<String, String[]> parameterMap = request.getParameterMap();
        String jsonString = JSONObject.toJSONString(parameterMap);
        log.info("企业微信回调参数：{},  解析参数：{}", jsonString, body);

        if (body == null) {
            Object result = qyapiUtil.verificationUrl(request);
            return result;
        }
        Map<String, String> resultMap = qyapiUtil.getRequestParameter(request, body);

        MessageBody messageBody = new MessageBody(resultMap.toString());
        qyapiUtil.sendWebhook("https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=196bca5d-fd60-459c-a2d8-1944843e496a",messageBody);

        return "success";
    }
}
